package com.reactim.message.repository;

import com.reactim.message.entity.Conversation;
import org.springframework.data.domain.Pageable;
import org.springframework.data.mongodb.repository.Query;
import org.springframework.data.mongodb.repository.ReactiveMongoRepository;
import org.springframework.stereotype.Repository;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

/**
 * 会话数据访问接口
 */
@Repository
public interface ConversationRepository extends ReactiveMongoRepository<Conversation, String> {
    
    /**
     * 根据会话ID查找会话
     */
    Mono<Conversation> findByConversationId(String conversationId);
    
    /**
     * 查找用户的所有会话
     */
    @Query("{'participants': ?0}")
    Flux<Conversation> findByParticipantsContaining(Long userId, Pageable pageable);
    
    /**
     * 查找私聊会话
     */
    @Query("{'type': 'PRIVATE', 'participants': {'$all': [?0, ?1]}}")
    Mono<Conversation> findPrivateConversation(Long userId1, Long userId2);
    
    /**
     * 查找群聊会话
     */
    Mono<Conversation> findByGroupIdAndType(Long groupId, Conversation.ConversationType type);
    
    /**
     * 查找用户最近的会话
     */
    @Query("{'participants': ?0}")
    Flux<Conversation> findRecentConversations(Long userId, Pageable pageable);
    
    /**
     * 统计用户会话数量
     */
    @Query(value = "{'participants': ?0}", count = true)
    Mono<Long> countUserConversations(Long userId);
    
    /**
     * 查找活跃会话（有消息的会话）
     */
    @Query("{'participants': ?0, 'messageCount': {'$gt': 0}}")
    Flux<Conversation> findActiveConversations(Long userId, Pageable pageable);
}